<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="hAdd">新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="queryParams.page"
                :page-sizes="[2, 3, 5, 10]"
                :page-size="queryParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑' : '新增'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="resetForm"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog = false">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoles, addRoles, getRolesDetails, editRoles, delRoles } from '@/api/settings'
export default {
  data() {
    return {
      // 收集表单数据
      roleForm: {
        name: '',
        description: ''
      },
      // 表单校验规则对象
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      isEdit: false,
      // 控制弹层的显示和隐藏
      showDialog: false,
      // 存储总条数
      total: 0,
      // 存储所有的角色数据,用于表格渲染
      list: [],
      // 请求参数
      queryParams: {
        page: 1,
        pagesize: 5
      }
    }
  },
  created() {
    this.loadRoleList()
    if (this.isEdit) {
      this.loadRoleForm()
    }
  },
  methods: {
    // 10.删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const res = await delRoles(id)
          console.log('delRoles', res)
          // 删除成功,提醒用户
          this.$message.success(res.data.message)
          // 重新渲染页面
          if (this.list.length === 1) {
            this.queryParams.page--
            if (this.queryParams.page <= 0) this.queryParams.page = 1
          }
          this.loadRoleList()
        } catch (err) {
          console.log('delRoles', err)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 9.关闭弹层时重置表单
    resetForm() {
      this.$refs.roleForm.resetFields()
      this.roleForm = { name: '', description: '' }
    },
    // 8.发送编辑请求
    async doEdit() {
      try {
        const { data: res } = await editRoles(this.roleForm)
        console.log('doEdit', res)
        // 重新渲染表格
        this.loadRoleList()
        // 关闭表单
        this.showDialog = false
      } catch (error) {
        console.log('doEdit', error)
      }
    },
    // 7.编辑表单时,先根据id获取角色详情,渲染表单
    async loadRoleForm() {
      try {
        const { data: res } = await getRolesDetails(this.roleForm.id)
        console.log('loadRoleForm', res)
      } catch (error) {
        console.log('loadRoleForm', error)
      }
    },
    // 6.发送新增请求
    async doAdd() {
      try {
        console.log('this.roleForm', this.roleForm)
        console.log('先')
        const { data: res } = await addRoles(this.roleForm)
        console.log('doAdd', res)
        // total++
        this.total++
        // 页面跳转到最后一页
        const maxPage = Math.ceil(this.total / this.queryParams.pagesize)
        this.queryParams.page = maxPage
        // 重新渲染页面
        this.loadRoleList()
        this.showDialog = false
      } catch (error) {
        console.log('doAdd', error)
      }
    },
    // 5.提交
    hSubmit() {
    // 兜底校验
      this.$refs.roleForm.validate((valid) => {
        if (!valid) return// 校验失败
        // 校验成功 ,发送请求
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 4.编辑
    hEdit(data) {
      this.showDialog = true
      this.isEdit = true
      this.roleForm = { ...data }
    },
    // 3.新增
    hAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    // 2.分页器
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.queryParams.page = 1
      this.queryParams.pagesize = val
      this.loadRoleList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.queryParams.page = val
      this.loadRoleList()
    },
    // 1.发送请求获取表格所有角色数据,渲染页面
    async loadRoleList() {
      try {
        const { data: res } = await getRoles(this.queryParams)
        console.log('getRoles', res.data.rows)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log('getRoles', error)
      }
    }
  }
}
</script>
